package com.tcl.mie.launcher.basehttp;

import com.squareup.okhttp.ResponseBody;

import java.util.HashMap;

/**
 * @Description json 网络数据加载
 * @author flying
 * @version 1.0
 * @Created on 2016/7/8.
 */
public class JsonLoader implements InterruptibleInternetLoader {

    final JsonProvider entityProvider;
    HttpLoader httpLoader;

    public JsonLoader(JsonProvider provider) {
        this.entityProvider = provider;
        httpLoader = new HttpLoader(entityProvider.getUrl());
        httpLoader.setLoadCallback(loadCallback);
    }

    @Override
    public boolean load() {
        httpLoader.cancel();
        HashMap<String, String> paramsMap = entityProvider.getParams();
        HashMap<String, byte[]> entityMap = null;

        return load(paramsMap, entityMap, entityProvider.isSupportPost());
    }

    public synchronized boolean load(HashMap<String, String> paramsMap,
                                     HashMap<String, byte[]> entityMap, boolean supportPost) {

        return httpLoader.load(paramsMap, entityMap, null, supportPost);
    }

    public synchronized boolean load(HashMap<String, String> paramsMap) {
        return load(paramsMap, null, false);
    }

    @Override
    public void cancel() {
        httpLoader.cancel();
    }

    private HttpLoader.LoadCallback loadCallback = new HttpLoader.LoadCallback() {
        @Override
        public void onLoaded(int err, ResponseBody entity) {
            if (entityProvider == null)
                return;
            try {
                if (err == HttpRequestResult.SUCCESS && entity != null) {
                    boolean ret = entityProvider.parse(entity.string());
                    if (ret)
                        entityProvider.onSuccess();
                    else
                        entityProvider.onFailed();
                } else
                    entityProvider.onFailed();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
}
